from flask import Flask,flash, url_for,request,redirect,send_from_directory
from flask import render_template
from werkzeug import secure_filename
import os
import UtilTool

UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])


app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

app.secret_key = UtilTool.createRandom()



basedir = os.path.abspath(os.path.dirname(__file__))
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != 'admin' or \
           request.form['password'] != 'secret':
            flash(u'Invalid password provided', 'error')
        else:
            flash('You were successfully logged in')
            return redirect(url_for('index'))
    return render_template('login.html', error=error)

@app.route('/user/<username>')
def profile(username): 
    return 'profile! %s' % username

@app.route('/user/<int:post_id>')
def show_user_id(post_id):
    return 'user id %s' % post_id

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
        print('file_dir: '+file_dir)
        if not os.path.exists(file_dir):
            os.makedirs(file_dir)
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            print('filename: '+filename)
            new_filename = '12'+'.txt'
            file.save(os.path.join(file_dir,new_filename))
            return redirect(url_for('uploaded_file',filename=new_filename))
        
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

@app.errorhandler(404)
def not_found(error):
    return render_template('hello.html'), 404

with app.test_request_context():
    BASE_DIR = os.path.realpath(os.path.dirname(__file__))
    print('path: '+BASE_DIR)
    print(url_for('static', filename='qq.txt'))

if __name__ == '__main__':
    app.run(debug=True)